package cn.itcast.jd.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Component
public class HttpUtils {

    private PoolingHttpClientConnectionManager cm;

    public HttpUtils(){
        this.cm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        this.cm.setMaxTotal(100);
        //设置主机最大连接数
        this.cm.setDefaultMaxPerRoute(10);
    }
    /**
     * 根据请求地址下载页面数据
     * @param url
     * @return页面数据
     */
    public String doGet(String url){
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //创建HttpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        System.out.println("httputil url === " + url);
        //设置请求信息
        httpGet.setConfig(this.getConfig());
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient发起请求，获取响应
             response = httpClient.execute(httpGet);
            //解析响应，返回结果
            if (response.getStatusLine().getStatusCode() == 200){
                //判断响应体Entity是否不为空，如果不为空就可以用EntityUtils
                if (response.getEntity() != null) {
                   /* String content = EntityUtils.toString(response.getEntity(), "utf8");
                    System.out.println("content ===== " + content);*/
                    HttpEntity httpEntity = response.getEntity();
                    System.out.println(EntityUtils.toString(httpEntity,"utf8"));
                    return httpEntity.toString();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return null;
    }


    /**
     * 下载图片
     * @param url
     * @return 图片名称
     */
    public String doGetImage(String url){
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //创建HttpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        //设置请求信息
        httpGet.setConfig(this.getConfig());
        CloseableHttpResponse response = null;
        OutputStream outputStream = null;
        try {
            //使用HttpClient发起请求，获取响应
            response = httpClient.execute(httpGet);
            //解析响应，返回结果
            if (response.getStatusLine().getStatusCode() == 200){
                //判断响应体Entity是否不为空，如果不为空就可以用EntityUtils
                if (response.getEntity() != null) {
                   // 下载图片
                   // 获取图片后缀
                    String extName = url.substring(url.lastIndexOf("."));
                   // 创建图片名，重命名图片
                    String picName = UUID.randomUUID().toString() + extName;
                   // 下载图片
                   // 声明OutPutStream
                    outputStream = new FileOutputStream(new File("C:\\Users\\gexia\\Desktop\\images"
                            + picName));
                    response.getEntity().writeTo(outputStream);
                   // 返回图片名称
                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null){
                    response.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 设置请求信息
     * @return
     */
    private RequestConfig getConfig() {
       /* RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(10000)     //创建连接的最长时间
                .setConnectionRequestTimeout(50000) //获取连接的最长时间
                .setSocketTimeout(10000)        //数据传输的最长时间
                .build();*/
        //配置请求信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //设置连接的最长时间
                .setConnectionRequestTimeout(500) //设置获取连接的最长时间
                .setSocketTimeout(10*1000) //设置数据传输的最长时间
                .build();
        return config;
    }

}
